1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | public class BST { int n; double[] p; double[] q; double[][] w; double[][] e; int[][] root; public void initialize() { n=7; p=new double[n+1]; q=new double[n+1]; w=new double[n+2][n+1]; e=new double[n+2][n+1]; root=new int[n+2][n+1]; double[] np={0.00,0.04,0.06,0.08,0.02,0.10,0.12,0.14}; double[] nq={0.06,0.06,0.06,0.06,0.05,0.05,0.05,0.05}; for (int i=0; i<=n; i++) { p[i]=np[i]; q[i]=nq[i]; } } public void compute() { int l,i,j,r; double t; double infinity=n+2; //an upper bound on the cost of a tree for (i=1; i<=n+1; i++) { e[i][i-1]=q[i-1]; w[i][i-1]=q[i-1]; } for (l=1; l<=n; l++) { for (i=1; i<=n-l+1; i++) { j=i+l-1; e[i][j]=infinity; w[i][j]=w[i][j-1]+p[j]+q[j]; for (r=i; r<=j; r++) { t=e[i][r-1]+e[r+1][j]+w[i][j]; if (t<e[i][j]) { e[i][j]=t; root[i][j]=r; } } } } } protected double round(double x) { return Math.floor(x*1000.0+0.5)/1000.0; } public void printResult(java.io.PrintStream out) { int i,j; for (i=1; i<=n; i++) { for (j=1; j<=i-1; j++) out.print(" "); for (j=i; j<=n; j++) out.print(" "+round(e[i][j])); out.println(); } for (i=1; i<=n; i++) { for (j=1; j<=i-1; j++) out.print(" "); for (j=i; j<=n; j++) out.print(" "+root[i][j]); out.println(); } } public static void main(String[] args) { BST b=new BST(); b.initialize(); b.compute(); b.printResult(System.out); } } |